package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UploadUtil;
import cn.wolfcode.trip.base.util.COSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TencentCloudController {

    @Autowired
    private ServletContext ctx;


    @PostMapping("/tencentCloud/upload")
    @ResponseBody
    public Object uploadImage(MultipartFile pic){
        //格式为{"url":"/upload/...jpg","status":1},返回一个路径和状态
        //要返回一个对象封装,没有明确的对象,所以用map代替
        Map<String ,Object> map = new HashMap<>();
        COSClientUtil cos = new COSClientUtil();
        try {
            //图片保存
            //参数2:通过容器对象获取相对项目路径,(项目的真实部署路径)
            if(pic!=null&&pic.getSize()>0){
                String s = cos.uploadFile2Cos(pic);
                System.out.println(s);
                System.out.println(cos.getImgUrl(s));
                map.put("url", cos.getImgUrl(s));
                map.put("status", 1);//状态为1表示成功
            }
        }catch (Exception e){
            //如果是文件上传过程中报错,则返回一个状态为0,失败
            e.printStackTrace();
            map.put("url","");
            map.put("status",0);//0失败
        }
        //最后返回这个map
        return map;
    }
}
